﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;

namespace Game.PathFinder.Internal
{
    class NodeCollection : KeyedCollection<Point, Node>
    {
        readonly List<Node> _sorted = new List<Node>();
        readonly Dictionary<Point, Node> _map = 
            new Dictionary<Point, Node>();
        
        protected override Point GetKeyForItem(Node item)
        {
            return item.Point;
        }
        
        public bool ContainsNode(Node node)
        {
            return _map.ContainsKey(node.Point);
        }
        
        public Node First
        {
            get
            {
                if (_sorted.Count == 0)
                {
                    return null;
                }

                return _sorted[0];
            }
        }
        
        protected override void InsertItem(int index, Node item)
        {
            int insertAt = 0;
            foreach(var n in _sorted)
            {
                if (item.Cost < n.Cost)
                {
                    break;
                }

                insertAt++;
            }

            _sorted.Insert(insertAt, item);
            
            _map.Add(item.Point, item);
            base.InsertItem(index, item);
        }
        
        protected override void RemoveItem(int index)
        {
            _sorted.Remove(this[index]);
            _map.Remove(this[index].Point);
            base.RemoveItem(index);
        }
        
        protected override void ClearItems()
        {
            _map.Clear();
            _sorted.Clear();
            base.ClearItems();
        }
    }
        
}
